package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.application.LPKeyBoardApp;
import com.chhuang.ewcrm.bean.DeliveryBean;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.bean.WeighTypeBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WCustomerDao;
import com.chhuang.ewcrm.dao.WLicensePlateDao;
import com.chhuang.ewcrm.dao.WWeighTempDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.string.StringUtil;
import com.chhuang.ewcrm.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

import static javafx.application.Platform.runLater;

/**
 * 过磅临时数据维护
 */
public class WeighTempController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(WeighTempController.class);

    @FXML
    private ComboBox<WeighTypeBean> weighTypeComboBox;
    @FXML
    private ComboBox<WLicensePlate> lprComboBox;
    @FXML
    private JFXButton lpKeyBoardJFXButton;
    private StringProperty lptext = new SimpleStringProperty();//车牌字符串
    @FXML
    private ComboBox<EWarehouse> warehouseComboBox;
    @FXML
    private ComboBox<EWarehouse> warehouse1ComboBox;
    @FXML
    private ComboBox<WCustomer> customerComboBox;
    @FXML
    private ComboBox<EGoods> goodsComboBox;
    @FXML
    private ComboBox<EGoods> goods1ComboBox;
    @FXML
    private ComboBox<SysUser> salesmanComboBox;
    @FXML
    private ComboBox<SysUser> chargemanComboBox;

    @FXML
    private FlowPane warehouse1FlowPane;
    @FXML
    private FlowPane customerFlowPane;
    @FXML
    private FlowPane goods1FlowPane;
    @FXML
    private FlowPane salesmanFlowPane;

    @FXML
    private TextField grossWeightTextField;
    @FXML
    private TextField tareWeightTextField;
    @FXML
    private TextField impurityWeightTextField;
    @FXML
    private TextField netWeightTextField;
    @FXML
    private TextField priceTextField;
    @FXML
    private TextField amountTextField;
    @FXML
    private TextField remarkTextField;
    @FXML
    private TextField enterTimeTextField;

    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private JFXButton delJFXButton;

    @FXML
    private ComboBox<WeighTypeBean> queryWeighTypeComboBox;
    @FXML
    private ComboBox<String> queryLprComboBox;
    @FXML
    private ComboBox<String> queryWarehouseComboBox;
    @FXML
    private HBox queryCustomerHBox;
    @FXML
    private ComboBox<String> queryCustomerComboBox;
    @FXML
    private ComboBox<String> queryGoodsComboBox;
    @FXML
    private HBox querySalesmanHBox;
    @FXML
    private ComboBox<String> querySalesmanComboBox;
    @FXML
    private ComboBox<String> queryChargemanComboBox;
    @FXML
    private DateTimePicker enterTimeStartPicker;
    private ObjectProperty<LocalDateTime> enterTimeStart;
    @FXML
    private DateTimePicker enterTimeEndPicker;
    private ObjectProperty<LocalDateTime> enterTimeEnd;

    @FXML
    private JFXButton seachJFXButton;

    @FXML
    private TableView<WWeighTemp> tableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;
    @FXML
    private Pagination pagination;

    @FXML
    private FlowPane priceFlowPane;
    @FXML
    private FlowPane deductionMoneyFlowPane;
    @FXML
    private FlowPane amountFlowPane;
    @FXML
    private FlowPane isDeliveryFlowPane;
    @FXML
    private ComboBox<DeliveryBean> isDeliveryComboBox;
    @FXML
    private TextField deductionMoneyTextField;
    @FXML
    private Label amountLabel;


    //编辑区绑定对象 清空是也要清空，双击选择时要赋值
    private WWeighTemp wWeighTempBinder = null;
    private final QueryBean<WWeighTemp> queryBean = new QueryBean<>();

    private final NumberTextFilter numberTextFilter = new NumberTextFilter();
    private final WLicensePlateDao wLicensePlateDao = App.getSession().getMapper(WLicensePlateDao.class);
    private final WCustomerDao wCustomerDao = App.getSession().getMapper(WCustomerDao.class);
    private final WWeighTempDao wWeighTempDao = App.getSession().getMapper(WWeighTempDao.class);

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("过磅类别","weighType", true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return Constants.WEIGH_TYPES.get((int)o).getWeighTypeName();
                }
            },
            new TableColumnBean("车牌号","licensePlate"),
            new TableColumnBean("仓库","warehouseName", true),
            new TableColumnBean("客户","customerName"),
            new TableColumnBean("物品","goodsName", true),
            new TableColumnBean("原仓库","warehouse1Name"),
            new TableColumnBean("物品原名","goods1Name"),
            new TableColumnBean("毛重","grossWeight"),
            new TableColumnBean("皮重","tareWeight"),
            new TableColumnBean("扣重","impurityWeight"),
            new TableColumnBean("净重","netWeight"),
            new TableColumnBean("价格","price"),
            new TableColumnBean("扣款","deductionMoney"),
            new TableColumnBean("金额","amount"),
            new TableColumnBean("过磅员","weighmanName", true),
            new TableColumnBean("备注","remark", false),
            new TableColumnBean("负责人","chargemanName", true, false),
            new TableColumnBean("业务员","salesmanName", true, false),
            new TableColumnBean("进厂时间","enterTime", true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.YYYY_MM_DD_HH_MM_SS);
                }
            }
    };
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTable();
        //初始化过磅类别
        initWeighType();
        //初始化车牌
        initLp();
        //初始化仓库
        initWarehouse();
        //初始化客户
        initCustomer();
        //初始化商品
        initGoods();
        //初始化业务员和负责人
        initMan();
        //是否是自提
        initIsDelivery();
        //初始化毛皮扣重
        initWeigh();
        //初始化价格扣款总价
        initPrice();
        //初始化按钮监听
        initListener();

        //初始化日期控件
        initDateTimePicker();
    }

    /**
     * 初始化表格
     */
    private void initTable() {
        //设置列
        List<TableColumn<WWeighTemp, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tcb : tableColumnBeans){
            TableColumn<WWeighTemp, Object> tableColumn = new TableColumn<>(tcb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tcb.getRecordName()));
            tableColumn.setSortable(tcb.isSort());
            tableColumn.setVisible(tcb.isVisible());
            tableColumn.setCellFactory(wWeighTempObjectTableColumn -> {
                TableCell<WWeighTemp, Object> cell = new TableCell<>(){
                    @Override
                    protected void updateItem(Object o, boolean b) {
                        super.updateItem(o, b);
                        if(b || o==null){
                            this.setText(null);
                        }else {
                            this.setText(tcb.format(o));
                        }
                    }
                };
                cell.setAlignment(Pos.CENTER);
                return cell;
            });
            tableColumns.add(tableColumn);
        }
        tableView.getColumns().addAll(tableColumns);//添加列

        //设置双击某一列
        tableView.setRowFactory(tableView -> {
            TableRow<WWeighTemp> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    wWeighTempBinder = row.getItem();
                    autoForm(wWeighTempBinder);
                }
            });
            return row;
        });

        tableView.setSortPolicy(tableView -> {
            ObservableList<TableColumn<WWeighTemp,?>> list = tableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<WWeighTemp,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        pagination.setMaxPageIndicatorCount(9);//数字按钮数量

        //获取表格数据
        getTableData();
    }

    //是否获取联动选择器（物品名称）开关
    private boolean isAutoForm = false;

    /**
     * 自动填写表单
     * @param weighTemp
     */
    private void autoForm(WWeighTemp weighTemp) {
        if(weighTemp==null) return; //状态不需要二次过磅
        isAutoForm = true;
        //车牌
        boolean isbreak = false;
        for (WLicensePlate item : lprComboBox.getItems()) {
            if (item.getWlpNumber().equals(weighTemp.getLicensePlate())) {
                lprComboBox.getSelectionModel().select(item);
                isbreak = true;
                break;
            }
        }
        if(!isbreak) lptext.setValue(weighTemp.getLicensePlate());
        //过磅类别
        for(WeighTypeBean item : weighTypeComboBox.getItems()){
            if(item.getWeighTypeId()-weighTemp.getWeighType()==0){
                weighTypeComboBox.getSelectionModel().select(item);
                break;
            }else {
                weighTypeComboBox.getSelectionModel().select(0);
            }
        }
        //仓库名称
        if(warehouseComboBox.getItems()!=null && !warehouseComboBox.getItems().isEmpty()) {
            if (StringUtils.isNotEmpty(weighTemp.getWarehouseId())) {
                for (EWarehouse item : warehouseComboBox.getItems()) {
                    if (weighTemp.getWarehouseId().equals(item.getWarehouseId())) {
                        warehouseComboBox.getSelectionModel().select(item);
                        break;
                    }
                }
            }else {
                warehouseComboBox.getSelectionModel().select(0);
            }
        }
        //物品名称
        getEGoods(weighTemp.getWeighType(), weighTemp.getWarehouseId(), weighTemp.getGoodsId());
        //负责人
        if(chargemanComboBox.getItems()!=null && !chargemanComboBox.getItems().isEmpty()){
            if(StringUtils.isNotEmpty(weighTemp.getChargemanId())){
                for(SysUser item: chargemanComboBox.getItems()){
                    if(weighTemp.getChargemanId().equals(item.getUserId())){
                        chargemanComboBox.getSelectionModel().select(item);
                        break;
                    }
                }
            }else {
                chargemanComboBox.getSelectionModel().select(0);
            }
        }

        if(weighTemp.getWeighType()<2) {//入库和出库
            //业务员
            if (salesmanComboBox.getItems() != null && !salesmanComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getSalesmanId())) {
                    for (SysUser item : salesmanComboBox.getItems()) {
                        if (weighTemp.getSalesmanId().equals(item.getUserId())) {
                            salesmanComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                } else {
                    salesmanComboBox.getSelectionModel().select(0);
                }
            }
            //是否自提
            if (weighTemp.getIsDelivery()) {
                isDeliveryComboBox.getSelectionModel().select(1);//是
            } else {
                isDeliveryComboBox.getSelectionModel().select(0);//否
            }
        }

        if(weighTemp.getWeighType()==2){//内部周转
            //原仓库名称
            if(warehouse1ComboBox.getItems()!=null && !warehouse1ComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getWarehouse1Id())) {
                    for (EWarehouse item : warehouse1ComboBox.getItems()) {
                        if (weighTemp.getWarehouse1Id().equals(item.getWarehouseId())) {
                            warehouse1ComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                }else {
                    warehouse1ComboBox.getSelectionModel().select(0);
                }
            }
            //原物品名称
            getEGoods1(weighTemp.getWarehouse1Id(), weighTemp.getGoods1Id());
        }else {//不是内部周转
            //客户名称
            if(customerComboBox.getItems()!=null && !customerComboBox.getItems().isEmpty()) {
                if (StringUtils.isNotEmpty(weighTemp.getCustomerId())) {
                    for (WCustomer item : customerComboBox.getItems()) {
                        if(weighTemp.getCustomerId().equals(item.getCustomerId())){
                            customerComboBox.getSelectionModel().select(item);
                            break;
                        }
                    }
                }else {
                    customerComboBox.setValue(null);
                }
            }
        }
        //毛重
        grossWeightTextField.setText(weighTemp.getGrossWeight()==null?null:weighTemp.getGrossWeight().toString());
        //扣重
        impurityWeightTextField.setText(weighTemp.getImpurityWeight()==null?null:weighTemp.getImpurityWeight().toString());

        if((weighTemp.getWeighType()==0 && !weighTemp.getIsDelivery()) || //入库 不是自提 需要写价格等
                (weighTemp.getWeighType()==1 && weighTemp.getIsDelivery()) || //出库 是自提 需要写价格等
                weighTemp.getWeighType()==2){ //内部周转 需要写价格等
            //价格
            priceTextField.setText(weighTemp.getPrice()==null?null:weighTemp.getPrice().toString());
            //扣款
            deductionMoneyTextField.setText(weighTemp.getDeductionMoney()==null?null:weighTemp.getDeductionMoney().toString());
        }

        if(weighTemp.getWeighType()==3){//其它过磅，过磅费
            amountTextField.setText(weighTemp.getAmount()==null?null:weighTemp.getAmount().toString());
        }

        //备注
        remarkTextField.setText(weighTemp.getRemark());

        //进厂时间
        enterTimeTextField.setText(DateUtil.date2String(weighTemp.getEnterTime(), DateUtil.YYYY_MM_DD_HH_MM_SS));

        isAutoForm = false;
    }

    /**
     * 获取列表数据
     */
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("enter_time desc");
        }
        PageInfo<WWeighTemp> pageInfo = PageHelper.startPage(queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy()).doSelectPageInfo(() ->
                wWeighTempDao.queryLike(queryBean.getQuery())
        );

        //总页数发生改变时从第一页开始
        if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
            queryBean.setPageNum(1);
            getTableData();
            return;
        }

        //一共多少条数据
        if(queryBean.getTotal()-pageInfo.getTotal()!=0){
            queryBean.setTotal(pageInfo.getTotal());
            totalLabel.setText(String.valueOf(queryBean.getTotal()));
        }

        //一共多少页
        if(queryBean.getPages()-pageInfo.getPages()!=0) {
            queryBean.setPages(pageInfo.getPages());
            pagesLabel.setText(String.valueOf(queryBean.getPages()));
            pagination.setPageCount(queryBean.getPages());
        }

        tableView.getItems().clear();
        if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty())
            tableView.getItems().addAll(pageInfo.getList());
    }

    /**
     * 是否是自提
     */
    private void initIsDelivery() {
        List<DeliveryBean> list = new LinkedList<>();
        list.add(new DeliveryBean(false, "否"));//0
        list.add(new DeliveryBean(true, "是"));//1
        isDeliveryComboBox.getItems().addAll(list);
        isDeliveryComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(DeliveryBean deliveryBean) {
                return deliveryBean==null?null:deliveryBean.getTitle();
            }

            @Override
            public DeliveryBean fromString(String s) {
                return null;
            }
        });
        isDeliveryComboBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue)->{
            WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
            if(weighTypeBean!=null)weighTypeAndIsDelivery(newValue.isDelivery(), weighTypeBean.getWeighTypeId());
        });
        isDeliveryComboBox.getSelectionModel().select(0);//默认选中第一项
    }

    /**
     * 过磅类别与是否自提联动
     * @param delivery
     * @param weighTypeId
     */
    private void weighTypeAndIsDelivery(boolean delivery, int weighTypeId){
        if(delivery){//是自提
            switch (weighTypeId){//入库自提的不需要填写金额
                case 0://入库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }else {
            switch (weighTypeId){//出库不是自提的不需要填写金额
                case 1://出库
                    priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                    deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                    amountFlowPane.setVisible(false); amountFlowPane.setManaged(false);
                    break;
                default://其它
                    priceFlowPane.setVisible(true); priceFlowPane.setManaged(true);
                    deductionMoneyFlowPane.setVisible(true); deductionMoneyFlowPane.setManaged(true);
                    amountFlowPane.setVisible(true); amountFlowPane.setManaged(true);
                    break;
            }
        }
    }

    /**
     * 加载车牌选择
     */
    private void loadLPRCombBox(){
        List<WLicensePlate> wLicensePlateList = wLicensePlateDao.query(null);
        if(wLicensePlateList!=null && !wLicensePlateList.isEmpty()){
            lprComboBox.getItems().addAll(wLicensePlateList);
            new AutoCompleteComboBoxListener<>(lprComboBox);

            for(WLicensePlate lp : wLicensePlateList){
                queryLprComboBox.getItems().add(lp.getWlpNumber());
            }
            new AutoCompleteComboBoxListener<>(queryLprComboBox);
        }
    }

    /**
     * 初始化车牌
     */
    private void initLp() {
        loadLPRCombBox();

        //只能输入大写
        UpCastTextFilter upCastTextFilter = new UpCastTextFilter();
        lprComboBox.getEditor().setTextFormatter(new TextFormatter<>(upCastTextFilter));

        queryLprComboBox.getEditor().setTextFormatter(new TextFormatter<>(upCastTextFilter));

        lprComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WLicensePlate wLicensePlate) {
                return wLicensePlate!=null?wLicensePlate.getWlpNumber():null;
            }

            //添加新值时，转对象
            @Override
            public WLicensePlate fromString(String s) {
                WLicensePlate wLicensePlate = null;
                if(StringUtils.isNotEmpty(s)){
                    wLicensePlate = new WLicensePlate();
                    wLicensePlate.setWlpNumber(s.toUpperCase());
                    List<WLicensePlate> wLicensePlates = wLicensePlateDao.query(wLicensePlate);
                    if(wLicensePlate!=null && !wLicensePlates.isEmpty()){
                        wLicensePlate = wLicensePlates.get(0);
                    }else {
                        wLicensePlate.setCreateTime(new Date());
                        wLicensePlateDao.insert(wLicensePlate);
//                        lprComboBox.getItems().add(wLicensePlate);
                        loadLPRCombBox();
                    }
                }
                return wLicensePlate;
            }
        });

        //弹出键盘输入车牌
        lpKeyBoardJFXButton.setOnAction(event -> new LPKeyBoardApp(lptext).start(new Stage()));
        //监听 车牌字符串 修改
        lptext.addListener((observableValue, s, t1) -> {
            if(StringUtils.isNotEmpty(t1)) {
                lprComboBox.getSelectionModel().select(lprComboBox.getConverter().fromString(t1));
            }
        });
    }

    /**
     * 初始化业务员和负责人
     */
    private void initMan() {
        SysUser voidUser = new SysUser();
        voidUser.setUsername("--请选择--");

        StringConverter<SysUser> converter = new StringConverter<>() {
            @Override
            public String toString(SysUser sysUser) {
                return sysUser==null?null:(sysUser.getFullname()==null?sysUser.getUsername():sysUser.getFullname());
            }

            @Override
            public SysUser fromString(String s) {
                return null;
            }
        };

        chargemanComboBox.setConverter(converter);
        chargemanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getChargerMans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取负责人请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()-> {
                                chargemanComboBox.getItems().addAll(users);
                                for(SysUser user : users){
                                    queryChargemanComboBox.getItems().add(user.getFullname()==null?user.getUsername():user.getFullname());
                                }
                                new AutoCompleteComboBoxListener<>(queryChargemanComboBox);
                            });
                        }
                    }
                });
        chargemanComboBox.getSelectionModel().select(0);

        salesmanComboBox.setConverter(converter);
        salesmanComboBox.getItems().add(voidUser);
        AppRequest.getInstance().getService().getSalesmans()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取业务员请求") {
                    @Override
                    protected void onHandleSuccess(List<SysUser> users) {
                        if(users!=null && !users.isEmpty()) {
                            runLater(()-> {
                                salesmanComboBox.getItems().addAll(users);
                                for(SysUser user : users){
                                    querySalesmanComboBox.getItems().add(user.getFullname()==null?user.getUsername():user.getFullname());
                                }
                                new AutoCompleteComboBoxListener<>(querySalesmanComboBox);
                            });
                        }
                    }
                });
        salesmanComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化商品
     */
    private void initGoods() {
        StringConverter<EGoods> converter = new StringConverter<>() {
            @Override
            public String toString(EGoods eGoods) {
                return eGoods==null?null:eGoods.getGoodsName();
            }

            @Override
            public EGoods fromString(String s) {
                return null;
            }
        };

        goodsComboBox.setConverter(converter);

        goods1ComboBox.setConverter(converter);

        for (int i=0;i<3;i++) {
            AppRequest.getInstance().getService().getGoods(i, null)
                    .compose(ServiceRxSchedulers.compose())
                    .subscribe(new ServiceSubscriber<>("获取物品"+i) {
                        @Override
                        protected void onHandleSuccess(List<EGoods> eGoodsList) {
                            if(eGoodsList!=null && !eGoodsList.isEmpty())
                                eGoodsList.forEach(item->
                                    runLater(()->queryGoodsComboBox.getItems().add(item.getGoodsName()))
                                );
                        }
                    });
        }
    }

    /**
     * 加载客户选择
     */
    private void loadCustomer(){
        List<WCustomer> wCustomerList = wCustomerDao.query(null);
        if(wCustomerList!=null && !wCustomerList.isEmpty()){
            customerComboBox.getItems().addAll(wCustomerList);
            new AutoCompleteComboBoxListener<>(customerComboBox);//自动完成功能

            for(WCustomer temp : wCustomerList){
                queryCustomerComboBox.getItems().add(temp.getCustomerName());
            }
            new AutoCompleteComboBoxListener<>(queryCustomerComboBox);
        }
    }

    /**
     * 初始化客户
     */
    private void initCustomer() {
        loadCustomer();

        customerComboBox.getEditor().setTextFormatter(new TextFormatter<>(new LengthTextFilter(127)));
        customerComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(WCustomer wCustomer) {
                return wCustomer==null?null:wCustomer.getCustomerName();
            }

            @Override
            public WCustomer fromString(String s) {
                WCustomer wCustomer = null;
                if(StringUtils.isNotEmpty(s)){
                    wCustomer = new WCustomer();
                    wCustomer.setCustomerName(s);
                    List<WCustomer> wCustomers = wCustomerDao.query(wCustomer);
                    if(wCustomers!=null && !wCustomers.isEmpty()){
                        wCustomer = wCustomers.get(0);
                    }else {
                        Date now = new Date();
                        wCustomer.setModifyTime(now);
                        wCustomer.setCreateTime(now);
                        wCustomerDao.insert(wCustomer);
//                        customerComboBox.getItems().add(wCustomer);
                        loadCustomer();
                    }
                }
                return wCustomer;
            }
        });
    }

    /**
     * 初始化仓库
     */
    private void initWarehouse() {
//        EWarehouse warehouseTemp = new EWarehouse();
//        warehouseTemp.setWarehouseName("--请选择--");
//        warehouseComboBox.getItems().add(warehouseTemp);
//        warehouse1ComboBox.getItems().add(warehouseTemp);

        AppRequest.getInstance().getService().getWarehouses()
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取所有仓库请求") {
                    @Override
                    protected void onHandleSuccess(List<EWarehouse> warehouses) {
                        if(warehouses!=null && !warehouses.isEmpty()) {
                            runLater(()->{
                                warehouse1ComboBox.getItems().addAll(warehouses);
                                warehouseComboBox.getItems().addAll(warehouses);

                                warehouseComboBox.getSelectionModel().select(0);
                                warehouse1ComboBox.getSelectionModel().select(0);

                                for(EWarehouse temp: warehouses){
                                    queryWarehouseComboBox.getItems().add(temp.getWarehouseName());
                                }
                            });
                        }
                    }
                });

        StringConverter<EWarehouse> converter = new StringConverter<>() {
            @Override
            public String toString(EWarehouse eWarehouse) {
                return eWarehouse==null?null:eWarehouse.getWarehouseName();
            }

            @Override
            public EWarehouse fromString(String s) {
                return null;
            }
        };

        warehouseComboBox.setConverter(converter);
        warehouse1ComboBox.setConverter(converter);

        warehouseComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            if(!isAutoForm) {
                WeighTypeBean weighTypeBean = weighTypeComboBox.getSelectionModel().getSelectedItem();
                //修改物品
                getEGoods(weighTypeBean.getWeighTypeId(), newValue == null ? null : newValue.getWarehouseId(), null);
            }
        });

        warehouse1ComboBox.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> {
            if(!isAutoForm) {
                //修改原物品
                getEGoods1(newValue == null ? null : newValue.getWarehouseId(), null);
            }
        });

//        warehouseComboBox.getSelectionModel().select(0);
//        warehouse1ComboBox.getSelectionModel().select(0);
    }

    private void getEGoods(int weightTypeId, String warehouseId, String goodsId){
        int typeId = 0;
        switch (weightTypeId){
            case 0,2:typeId=0;break;
            case 1:typeId=1;break;
            case 3:typeId=2;break;
        }
        //修改物品
        AppRequest.getInstance().getService().getGoods(typeId, warehouseId)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()->{
                            goodsComboBox.getItems().clear();
                            if(goodsList!=null && !goodsList.isEmpty()) {
                                goodsComboBox.getItems().addAll(goodsList);
                                goodsComboBox.getSelectionModel().select(0);
                                if(StringUtils.isNotEmpty(goodsId)){
                                    for(EGoods item: goodsComboBox.getItems()){
                                        if(goodsId.equals(item.getGoodsId())){
                                            goodsComboBox.getSelectionModel().select(item);
                                            break;
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
//        goodsComboBox.getSelectionModel().select(0);
    }

    private void getEGoods1(String warehouseId1, String goodsId){
        //修改原物品
        AppRequest.getInstance().getService().getGoods(1, warehouseId1)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取原物品名称请求") {
                    @Override
                    protected void onHandleSuccess(List<EGoods> goodsList) {
                        runLater(()-> {
                            goods1ComboBox.getItems().clear();
                            if (goodsList != null && !goodsList.isEmpty()) {
                                goods1ComboBox.getItems().addAll(goodsList);
                                goods1ComboBox.getSelectionModel().select(0);
                                if(StringUtils.isNotEmpty(goodsId)){
                                    for(EGoods item: goods1ComboBox.getItems()){
                                        if(goodsId.equals(item.getGoodsId())){
                                            goods1ComboBox.getSelectionModel().select(item);
                                            break;
                                        }
                                    }
                                }
                            }
                        });
                    }
                });
//        goods1ComboBox.getSelectionModel().select(0);
    }

    /**
     * 初始化重量输入框
     */
    private void initWeigh(){
        //毛重
        grossWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        grossWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //皮重
        tareWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        tareWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoWeigh();
        });
        //设置扣重只接收数字输入
        impurityWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改扣重时
        impurityWeightTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoWeigh();
            }
        });
        //净重
        netWeightTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        netWeightTextField.textProperty().addListener((observable, oldValue, newValue)->{
            autoMoney();
        });
    }

    /**
     * 初始化价格 扣款 总金额
     */
    private void initPrice() {
        //设置价格只接收数字
        priceTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        //修改价格时
        priceTextField.focusedProperty().addListener((observable, oldValue, newValue)->{
            if(!newValue) {
                autoMoney();
            }
        });

        //设置价格只接收数字
        deductionMoneyTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
        deductionMoneyTextField.focusedProperty().addListener((observableValue, aBoolean, t1) -> {
            if(!t1){
                autoMoney();
            }
        });

        //设置总价只接收数字
        amountTextField.setTextFormatter(new TextFormatter<String>(numberTextFilter));
    }

    /**
     * 联动重量 当毛重，皮重， 扣重 修改后 调用
     */
    private void autoWeigh(){
        String tareWeightStr = tareWeightTextField.getText();
        String grossWeightStr = grossWeightTextField.getText();
        if(StringUtils.isNotEmpty(tareWeightStr) && StringUtil.isPositiveNumber(tareWeightStr) &&
                StringUtils.isNotEmpty(grossWeightStr) && StringUtil.isPositiveNumber(grossWeightStr)){
            double tareWeight = Double.parseDouble(tareWeightStr);
            double grossWeight = Double.parseDouble(grossWeightStr);

            //扣重
            double impurityWeight = 0;
            String impurityWeightStr = impurityWeightTextField.getText();
            if(StringUtils.isNotEmpty(impurityWeightStr) && StringUtil.isPositiveNumber(impurityWeightStr))
                impurityWeight = Double.parseDouble(impurityWeightStr);

            //净重
            double netWeight = grossWeight-tareWeight-impurityWeight;
            netWeightTextField.setText(String.format("%.3f",netWeight));
        }
    }

    /**
     * 联动金额  当净重，价格 扣款 修改后 调用
     */
    private void autoMoney(){
        String netWeightStr = netWeightTextField.getText();
        WeighTypeBean weighTypeBean = weighTypeComboBox.getValue();
        if(StringUtils.isNotEmpty(netWeightStr) && StringUtil.isPositiveNumber(netWeightStr) &&
                weighTypeBean.getWeighTypeId()!=3){
            double netWeight = Double.parseDouble(netWeightStr);
            //扣款
            double deductionMoney = 0;
            String deductionMoneyStr = deductionMoneyTextField.getText();
            if(StringUtils.isNotEmpty(deductionMoneyStr) && StringUtil.isPositiveNumber(deductionMoneyStr))
                deductionMoney = Double.parseDouble(deductionMoneyStr);

            //价格存在 计算总价
            double price =0;
            String priceStr = priceTextField.getText();
            if(StringUtils.isNotEmpty(priceStr) && StringUtil.isPositiveNumber(priceStr))
                price = Double.parseDouble(priceStr);
            amountTextField.setText(String.format("%.2f",netWeight*price-deductionMoney));
        }
    }

    /**
     * 初始化过磅类别
     */
    private void initWeighType() {
        //过磅类别
        weighTypeComboBox.getItems().addAll(Constants.WEIGH_TYPES);
        weighTypeComboBox.setConverter(new StringConverter<>() {
            //把对象，设置显示值
            @Override
            public String toString(WeighTypeBean weighTypeBean) {
                return weighTypeBean==null?null:weighTypeBean.getWeighTypeName();
            }
            //添加新值时，转对象
            @Override
            public WeighTypeBean fromString(String s) {return null;}
        });
        weighTypeComboBox.getSelectionModel().selectedItemProperty().addListener(
                (ObservableValue<? extends WeighTypeBean> observableValue, WeighTypeBean oldWtb, WeighTypeBean newWtb)-> {
                    DeliveryBean delivery = isDeliveryComboBox.getSelectionModel().getSelectedItem();
                    if(delivery!=null)weighTypeAndIsDelivery(delivery.isDelivery(), newWtb.getWeighTypeId());

                    if(newWtb.getWeighTypeId()<2){//入库 或 出库
                        salesmanFlowPane.setVisible(true); salesmanFlowPane.setManaged(true);
                        isDeliveryFlowPane.setVisible(true);isDeliveryFlowPane.setManaged(true);
                        if(!isAutoForm)isDeliveryComboBox.getSelectionModel().select(newWtb.getWeighTypeId());
                    }else {
                        salesmanFlowPane.setVisible(false); salesmanFlowPane.setManaged(false);
                        isDeliveryFlowPane.setVisible(false);isDeliveryFlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==2){//内部周转
                        warehouse1FlowPane.setVisible(true); warehouse1FlowPane.setManaged(true);
                        customerFlowPane.setVisible(false); customerFlowPane.setManaged(false);
                        goods1FlowPane.setVisible(true); goods1FlowPane.setManaged(true);
                    }else {
                        warehouse1FlowPane.setVisible(false);  warehouse1FlowPane.setManaged(false);
                        customerFlowPane.setVisible(true); customerFlowPane.setManaged(true);
                        goods1FlowPane.setVisible(false); goods1FlowPane.setManaged(false);
                    }

                    if(newWtb.getWeighTypeId()==3){//其它过磅
                        priceFlowPane.setVisible(false); priceFlowPane.setManaged(false);
                        deductionMoneyFlowPane.setVisible(false); deductionMoneyFlowPane.setManaged(false);
                        amountLabel.setText("过磅费：");amountTextField.setEditable(true);
                        amountTextField.setStyle("");
                    }else {
                        amountLabel.setText("总 价 ：");amountTextField.setEditable(false);
                        amountTextField.setStyle("-fx-background-color: gainsboro;");
                    }

                    //修改物品
                    if(!isAutoForm) {//双击表单时不需要联动
                        EWarehouse warehouse = warehouseComboBox.getValue();
                        getEGoods(newWtb.getWeighTypeId(), warehouse == null ? null : warehouse.getWarehouseId(), null);
                    }
                }
        );
        weighTypeComboBox.getSelectionModel().select(0);//默认选中第一项

        WeighTypeBean voidItem = new WeighTypeBean();
        voidItem.setWeighTypeName("--请选择--");
        queryWeighTypeComboBox.getItems().add(voidItem);
        queryWeighTypeComboBox.getItems().addAll(Constants.WEIGH_TYPES);
        queryWeighTypeComboBox.setConverter(new StringConverter<>() {
            @Override
            public String toString(WeighTypeBean weighTypeBean) {
                return weighTypeBean==null?null:weighTypeBean.getWeighTypeName();
            }

            @Override
            public WeighTypeBean fromString(String s) {
                return null;
            }
        });
    }

    /**
     * 初始化日期控件
     */
    private void initDateTimePicker(){
        enterTimeStartPicker.setPopupPreWidth(enterTimeStartPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        enterTimeStart = enterTimeStartPicker.dateTimeProperty();
        enterTimeEndPicker.setPopupPreWidth(enterTimeEndPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        enterTimeEnd = enterTimeEndPicker.dateTimeProperty();
    }

    /**
     * 按钮监听
     */
    private void initListener() {
        //每页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        //点击分页按钮监听
        pagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            getTableData();
        });

        //点击保存
        saveJFXButton.setOnAction(event -> {
            if(wWeighTempBinder!=null && StringUtils.isNotEmpty(wWeighTempBinder.getWeighId())){
                Integer weighType = weighTypeComboBox.getValue().getWeighTypeId();
                boolean isDelivery = isDeliveryComboBox.getValue().isDelivery();

                wWeighTempBinder.setWeighType(weighType);
                wWeighTempBinder.setLicensePlate(lprComboBox.getValue().getWlpNumber());
                wWeighTempBinder.setWarehouseId(warehouseComboBox.getValue().getWarehouseId());
                wWeighTempBinder.setWarehouseName(warehouseComboBox.getValue().getWarehouseName());
                wWeighTempBinder.setGoodsId(goodsComboBox.getValue().getGoodsId());
                wWeighTempBinder.setGoodsName(goodsComboBox.getValue().getGoodsName());
                if(StringUtils.isNotEmpty(chargemanComboBox.getValue().getUserId())) {
                    wWeighTempBinder.setChargemanId(chargemanComboBox.getValue().getUserId());
                    wWeighTempBinder.setChargemanName(chargemanComboBox.getValue().getFullname() == null ? chargemanComboBox.getValue().getUsername() : chargemanComboBox.getValue().getFullname());
                }
                if(weighType<2) {//入库和出库
                    //业务员
                    if(StringUtils.isNotEmpty(salesmanComboBox.getValue().getUserId())) {
                        wWeighTempBinder.setChargemanId(salesmanComboBox.getValue().getUserId());
                        wWeighTempBinder.setChargemanName(salesmanComboBox.getValue().getFullname() == null ? salesmanComboBox.getValue().getUsername() : salesmanComboBox.getValue().getFullname());
                    }
                    //是否自提
                    wWeighTempBinder.setIsDelivery(isDelivery);
                }

                WCustomer customer = customerComboBox.getValue();
                if(weighType==2){//内部周转
                    //原仓库名称
                    wWeighTempBinder.setWarehouse1Id(warehouse1ComboBox.getValue().getWarehouseId());
                    wWeighTempBinder.setWarehouse1Name(warehouse1ComboBox.getValue().getWarehouseName());
                    //原物品名称
                    wWeighTempBinder.setGoods1Id(goods1ComboBox.getValue().getGoodsId());
                    wWeighTempBinder.setGoods1Name(goods1ComboBox.getValue().getGoodsName());
                }else if(customer!=null){//不是内部周转
                    //客户名称
                    wWeighTempBinder.setCustomerId(customer.getCustomerId());
                    wWeighTempBinder.setCustomerName(customer.getCustomerName());
                    wWeighTempBinder.setCustomerPhone(customer.getCustomerPhone());
                }
                //扣重
                wWeighTempBinder.setImpurityWeight(impurityWeightTextField.getText()==null?null:Double.parseDouble(impurityWeightTextField.getText()));

                if((weighType==0 && !isDelivery) || //入库 不是自提 需要写价格等
                        (weighType==1 && isDelivery) || //出库 是自提 需要写价格等
                        weighType==2){ //内部周转 需要写价格等
                    //价格
                    wWeighTempBinder.setPrice(priceTextField.getText()==null?null:Double.parseDouble(priceTextField.getText()));
                    //扣款
                    wWeighTempBinder.setDeductionMoney(deductionMoneyTextField.getText()==null?null:Double.parseDouble(deductionMoneyTextField.getText()));
                }

                if(weighType==3){//其它过磅，过磅费
                    wWeighTempBinder.setAmount(amountTextField.getText()==null?null:Double.parseDouble(amountTextField.getText()));
                }

                //备注
                wWeighTempBinder.setRemark(remarkTextField.getText());

                wWeighTempDao.update(wWeighTempBinder);
                getTableData();
                resetForm();
            }else {
                MyAlert.showAlert("提示","没有选中要修改的过磅记录","请先双击表格中某一行要修改的过磅记录");
            }
        });

        //点击删除
        delJFXButton.setOnAction(event -> {
            if(wWeighTempBinder!=null && StringUtils.isNotEmpty(wWeighTempBinder.getWeighId())){
                wWeighTempDao.deleteById(wWeighTempBinder.getWeighId());
                getTableData();
                resetForm();
            }else {
                MyAlert.showAlert("提示","没有选中要删除的过磅记录","请先双击表格中某一行要删除的过磅记录");
            }
        });

        //查询
        seachJFXButton.setOnAction(event -> {
            WWeighTemp wWeighTemp = new WWeighTemp();

            WeighTypeBean weighTypeBean = queryWeighTypeComboBox.getValue();
            wWeighTemp.setWeighType(weighTypeBean==null?null:weighTypeBean.getWeighTypeId());

            wWeighTemp.setLicensePlate(StringUtils.isEmpty(queryLprComboBox.getValue())?null:queryLprComboBox.getValue());
            wWeighTemp.setCustomerName(StringUtils.isEmpty(queryCustomerComboBox.getValue())?null:queryCustomerComboBox.getValue());
            wWeighTemp.setWarehouseName(StringUtils.isEmpty(queryWarehouseComboBox.getValue())?null:queryWarehouseComboBox.getValue());
            wWeighTemp.setGoodsName(StringUtils.isEmpty(queryGoodsComboBox.getValue())?null:queryGoodsComboBox.getValue());
            wWeighTemp.setSalesmanName(StringUtils.isEmpty(querySalesmanComboBox.getValue())?null:querySalesmanComboBox.getValue());
            wWeighTemp.setChargemanName(StringUtils.isEmpty(queryChargemanComboBox.getValue())?null:queryChargemanComboBox.getValue());

            if(!enterTimeStartPicker.isVoid())
                wWeighTemp.setEnterTimeStart(DateUtil.localDateTime2Date(enterTimeStart.get()));
            if(!enterTimeEndPicker.isVoid())
                wWeighTemp.setEnterTimeEnd(DateUtil.localDateTime2Date(enterTimeEnd.get()));
            queryBean.setQuery(wWeighTemp);
            getTableData();
        });
    }

    private void resetForm() {
        lprComboBox.setValue(null);
        weighTypeComboBox.getSelectionModel().select(0);
        warehouseComboBox.getSelectionModel().select(0);
        warehouse1ComboBox.getSelectionModel().select(0);
        customerComboBox.setValue(null);
        goodsComboBox.getSelectionModel().select(0);
        goods1ComboBox.getSelectionModel().select(0);
        salesmanComboBox.getSelectionModel().select(0);
        isDeliveryComboBox.getSelectionModel().select(0);
        chargemanComboBox.getSelectionModel().select(0);
        grossWeightTextField.clear();
        tareWeightTextField.clear();
        impurityWeightTextField.clear();
        netWeightTextField.clear();
        priceTextField.clear();
        deductionMoneyTextField.clear();
        amountTextField.clear();
        remarkTextField.clear();
        enterTimeTextField.clear();
        wWeighTempBinder = null;
    }
    @Override
    public void close() {

    }
}
